<template>
  <div class="backgroundf5f5f5f" style="height: 100%">
    <my-header backBtn>
      <div slot="title">
       设置家庭地址
      </div>
    </my-header>
    <div v-show="postype" style="width: 0px;height: 20px;"/>
    <baidu-map class="bm-view"
               :style="'height:'+height+'px;'"
               :zoom="zoom"
               :center="center"
               @ready="handlerMap"
               :scroll-wheel-zoom="true"
               @click="click_map"
               ak="wpjzuT9FyGlqzF9ZeolLwmWZXRz2XZst">
      <bm-local-search :keyword="keyword" :autoViewport="true" :panel="false" :pageCapacity="1" @searchcomplete="searchcomplete" ></bm-local-search>
      <bm-circle :center="circlePath.center" :radius="circlePath.radius" :stroke-color="stroke_color"
                 :stroke-opacity="stroke_opacity" :stroke-weight="stroke_weight" :editing="false" @lineupdate="updateCirclePath"></bm-circle>
      <bm-control :offset="{width: '100px', height: '100px'}" class="footer2" style="width: 100%">

        <div v-show="postype" class="backgroundf5f5f5f" style="height:50.5px;width: 100%;">
          <div class="small" >
            <div style="padding: 10px;line-height: 30px;width: 100%">
              <p v-show="addresstype===1" style="float: left;height: 30px;">家庭：</p>
              <p v-show="addresstype===2" style="float: left;height: 30px;">学校：</p>
              <bm-auto-complete v-model="keyword" :sugStyle="{zIndex: 1}">
                <input placeholder="请输入地名关键字" :key="circlePath.title" :value="circlePath.title"
                       style="height: 30px; width: 80%;border:none;font-size: 1.6rem;"/>
              </bm-auto-complete>
            </div>
          </div>
        </div>

      </bm-control>
    </baidu-map>
    <div v-show="postype">
        <div style="width: 0px;height: 40px;"/>

        <div class="small backgroundf5f5f5f" style="padding: 0px;height: 5rem;" >
            <div style="float: left">
              <button class="weui-btn" type="default" @click="myaddup" style="width: 15rem;background: white;color: #4a4a4a;font-weight:400;" >我的位置</button>
            </div>
            <div style="float: right;">
              <button class="weui-btn" type="default" @click="mapclick" style="width: 15rem;background: white;color: #4a4a4a;font-weight:400;" >地图选点</button>
            </div>
        </div>

        <div style="width: 0px;height: 20px;"/>

        <div style="width: 100%;color: red;font-size: 10px;">我们将严格准许你相关法律法规保护您的个人信息！</div>
        <div style="width: 0px;height: 20px;"/>

        <div v-show="type" class="small" style="padding-top: 10px;">
          <div v-for="(ite,index) in addressdata" :key="index">
            <div class="title-test" style="border-bottom: 1px solid;border-bottom: 2px solid #f7f7f7" @click="adsubmit(ite)">
              <div style="float: left;display: table;width: 40px;" >
                <img src="../../../static/img/icon/icon24.png" style="margin: 15px auto" width="15px" height="15px"/>
              </div>
              <div class="title-test" style="text-align: left;margin-top: 3px;">
                <div class="fonttext" style="font-size: 17px;" :key="ite.title">{{ite.title}}</div>
                <div class="fonttext" style="font-size: 12px;margin-top: 2px;color: #757575" :key="ite.address">{{ite.address}}</div>
              </div>
              <div></div>
            </div>
          </div>
        </div>
    </div>
    <div v-show="!postype">
      <div class="small" style="padding-top: 10px;">
        <div v-for="(ite,index) in addressdata" :key="index">
          <div class="title-test" style="height: 70px;border-bottom: 1px solid;border-bottom: 2px solid #f7f7f7" >
            <div style="float: left;display: table;width: 10%;height: 70px;" >
              <img src="../../../static/img/icon/icon24.png" style="margin: 20px auto" width="15px" height="15px"/>
            </div>
            <div class="title-test" style="height: 70px;float:left;text-align: left;width: 65%;">
              <div class="fonttext" style="font-size: 17px; margin-top: 3px;" :key="ite.title">{{ite.title}}</div>
              <div class="fonttext" style="font-size: 12px;margin-top: 2px;color: #757575" :key="ite.address">{{ite.address}}</div>
            </div>
            <div style="float: left;height: 70px;width: 20%;">
              <button class="weui-btn"  style="width: 50px;height:20px;background: #07c160;
              color: white;font-weight:400;font-size: 10px; padding: 0;margin: 18px auto;" @click="adsubmit(ite)">确认点选</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {BaiduMap, BmMarker, BmControl, BmLocalSearch, BmAutoComplete, BmCircle} from 'vue-baidu-map'
  import wx from "weixin-js-sdk";
  import Axios from 'axios/index'
  import Cookies from 'js-cookie';

  export default {
    components: {
      BaiduMap,
      BmMarker,
      BmControl,
      BmLocalSearch,
      BmAutoComplete,
      BmCircle
    },
    prop: {
      height: {
        type: String,
        default: '800'
      }
    },
    name: "GpsAQAddress",
    data(){
      return{
        postype:true,
        mytype:false,
        center: '',
        zoom: 18,
        height:50.5,
        //height: document.body.clientHeight-300,
        width: document.body.clientWidth,
        type:false,
        student_id:'',
        BMap:null,
        map:null,
        addresstype:'',
        stroke_color:'blue',
        stroke_opacity:"0.5",
        stroke_weight:'2',
        addressdata:[],
        overlayLabel:null,
        circlePath: {
          center: {
            lng: '',
            lat: ''
          },
          radius: 0,
          title:''
        },
        keyword: '',
        homeCirclePath: {
          center: {
            lng: '',
            lat: ''
          },
          radius: 100,
          name:''
        },
        schoolCirclePath: {
          center: {
            lng: '',
            lat: ''
          },
          radius: 100,
          name:''
        },
      }
    },
    methods:{
      //地图点选显示
      mapclick(){
        this.height = document.body.clientHeight-300;
        this.postype=false;
      },
      //数据处理，给文本框和地图赋初始值
      updatedata(data){
        //如果值为空获取用户当前位置
        if(data.name===''){
          this.myposition();
        }else{
          //不为空赋值
          this.circlePath.title = data.name;
          this.circlePath.center.lat = data.center.lat;
          this.circlePath.center.lng = data.center.lng;
          //获取附近建筑
          this.Click_address(data.center);
        }
      },
      myaddup(){
        this.mytype=true;
        this.myposition();
      },
      //获取用户当前微信地址
      myposition(){
        //获取微信地址所需参数
        /*if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
          window.entryUrl = location.href.split('#')[0]
        }*/
        // 进行签名的时候  Android 不用使用之前的链接， ios 需要
        //let url = window.location.href;
        let signLink =  /(Android)/i.test(navigator.userAgent) ? window.location.href : this.$Cookies.get("indexurl");
        ///(Android)/i.test(navigator.userAgent) ? this.$weui.topTips('Android'+signLink): this.$weui.topTips('ios'+signLink);
        /*this.$weui.dialog({
          title: '提示',
          content: signLink
        })*/
        //let thisPageUrl = location.href.split('#')[0];
        //thisPageUrl = "http://meramipoppu.club/wechat/GpsAQ-Address"
        this.$http.securityfenceaddressBind({url: signLink}).then(res=>{
          this.getaddress(res.data);
        })
      },
      getaddress(rs){
        //调用微信接口，
        wx.config({
          debug:false,
          appId:rs.appId,
          timestamp:rs.timestamp,
          nonceStr:rs.nonceStr,
          signature: rs.signature,
          jsApiList:['getLocation']
        })
        /*wx.ready(function () {
          wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            console.log("wx.error", res);
          });
        });*/
        this.Location();
      },
      Location(){//获取到当前的地址，传入坐标类型
        wx.ready(()=> {
          wx.getLocation({
            //type:'WGS84',//地图坐标不同地图不同坐标
            success:(res => {
              //坐标转化
              this.coordinate(res.longitude,res.latitude);
            })
          });
        });
      },
      //百度坐标api转化
      coordinate(lng,lat){
        //创建坐标
        let ggPoint = new BMap.Point(lng,lat);
        let convertor = new BMap.Convertor();
        let pointArr = [];
        pointArr.push(ggPoint);
        convertor.translate(pointArr, 1, 5, data=>{
          //this.$weui.topTips("lat:"+data.points[0].lat+"=========>lng:"+data.points[0].lng);
          if(data.points){
            let points = data.points[0];
            //数据处理
            this.Click_address({lat:points.lat,lng:points.lng});
            if(this.mytype){
              this.confirm_submit({title:this.addressdata[0].title,lat:points.lat,lng:points.lng});
            }
          }
        });
       /* let bd09 = this.wgs84togcj02tobd09(108.30656,22.803423)
        this.Click_address({lat:bd09.latitude,lng:bd09.longitude});*/
      },
      //根据经纬度获取用户附近建筑
      Click_address(e){
        let point = new BMap.Point(e.lng,e.lat);
        let gc = new BMap.Geocoder();
        //更新地图位置
        this.center = point;
        //通过金纬度获取地址
        gc.getLocation(point,(e)=>{
          let data=[]
          //判断是否附近无建筑，写入当前位置信息
          if(e.surroundingPois.length===0&&e.address!==""){
            data[0]= {
              title: e.address,
              address: e.address,
              center: e.point
            }
          }
          for (let i=0;i<e.surroundingPois.length;i++){
            data[i]={
              title:e.surroundingPois[i].title,
              address:e.surroundingPois[i].address,
              center:e.surroundingPois[i].point
            }
            if(i===2)break;
          }
          //如果没有值直接结束
          if(data.length===0)return
          this.addressdata = data;
          this.type=true;
        })
      },
      //附近点选
      adsubmit(rs){
        this.confirm_submit({title:rs.title,lng:rs.center.lng,lat:rs.center.lat})
      },
      //确认提交
      confirm_submit(rs){
        this.$weui.dialog({
          title: '提示',
          content: '是否确认选择:'+rs.title+'地点' ,
          buttons: [{
            label: '取消',
            type: 'default',
          }, {
            label: '确定',
            type: 'primary',
            onClick: () => {
              this.submit({
                name:rs.title,
                lng:rs.lng,
                lat:rs.lat
              });
            }
          }]
        })
      },
      //提交
      submit(res){
        if(this.addresstype===1){
          let data = {
            id : this.student_id,
            sfFamilyName : res.name,
            sfFamilyLng : res.lng,
            sfFamilyLat : res.lat
          }
          //数据提交
          this.$http.securityfenceHomeBind(data).then(resp => {
            this.$weui.toast(resp.msg);
            if(resp.code===200){
              this.$router.go(-1)
            }
          });
        }else {
          let data = {
            id: this.student_id,
            sfSchoolName: res.name,
            sfSchoolLng: res.lng,
            sfSchoolLat: res.lat
          }
          //数据提交
          this.$http.securityfenceSchoolBind(data).then(resp => {
            this.$weui.toast(resp.msg);
            if(resp.code===200){
              this.$router.go(-1)
            }
          });
        }
      },
      searchcomplete(e) {
        this.$nextTick(() => {
          if (e && e.Hr) {
            this.center = e.Hr[0].point;  //这里获取了检索的位置并跳转
            this.circlePath.center = e.Hr[0].point;
            this.circlePath.title = e.Hr[0].title;
            //更新选项
            this.Click_address(e.Hr[0].point);
            this.confirm_submit({title:e.Hr[0].title,lng:e.Hr[0].point.lng,lat:e.Hr[0].point.lat});
          }
        });
      },
      updateCirclePath (e) {
        if(this.overlayLabel != null){
          this.map.removeOverlay(this.overlayLabel);
        }
        this.overlayLabel = new BMap.Circle(this.center, 0, {strokeColor:"blue",strokeWeight:2,strokeOpacity:0.5});
      },
      handlerMap({BMap, map}) {
        this.map = map;
        this.BMap = BMap;
        //添加空间
        this.addControl();
      },
      addControl(){
        // 添加比例尺控件
        let scaleCtrl = new BMap.ScaleControl();
        // 添加比例尺控件
        this.map.addControl(scaleCtrl);
      },
      click_map(rs){
        var lat = rs.point.lat;
        var lng = rs.point.lng;
        //更新附近建筑
        this.Click_address(rs.point)
      },
    }, mounted() {
      //获取传入的数据
      let data = this.$route.query;
      this.student_id = data.student_id;
      this.addresstype  = data.addresstype;
      //根据传过来的状态判断是家庭还是学校,传入方法更新文本框和地图位置
      this.updatedata(data.addresstype===1?data.homeCirclePath:data.schoolCirclePath);

      /*this.homeCirclePath = data.homeCirclePath;
      this.schoolCirclePath = data.schoolCirclePath;
      //获取用户地址
      //this.myposition()
      //根据传入位置坐标修改地图位置
      if(data.student_id===1){
        this.circlePath.title = this.homeCirclePath.name;
        this.center = data.homeCirclePath.center;
      }else{
        this.circlePath.title = this.schoolCirclePath.name;
        this.center = data.schoolCirclePath.center;
      }*/

      //this.Click_address({latitude:22.55100,longitude:113.90534});*/

    }
  }
</script>

<style scoped>
  .small{
    width: calc(100% - 2rem);
    margin: 0 auto auto 1rem;
    background: #FFFFFF;
    border-radius: 6px;
    font-size: 1.6rem;
    padding: 0 1rem;
    box-sizing: border-box;
    justify-content: space-between;
  }
  .backgroundf5f5f5f{
    background: #f5f5f5;
  }
  .currency{
    width: calc(100% - 2rem);
    height:45px; background: #fff;
    border-bottom: 1px solid rgba(238, 238, 238, 1);
  }
  .title-test{
    height: 70px;
  }
  .fonttext{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
